var Question = mongoose.model('question');
var Dic = mongoose.model('masterData_Dictionaries');
var Community = mongoose.model('community');
var Users = mongoose.model('user');
var async = require('async');
var moment = require('moment');
var ugcIndex = mongoose.model('system_ugcIndex');
var neighbourActivity = mongoose.model('activity_neighbour');
var questionStore = mongoose.model('questionstore');
var User = mongoose.model('user');
var Card = mongoose.model('community_card');

exports.backPostQuestionService = function (input, callback) {

    input.desc = input.desc.replace(/[\n\r]{2,}/g, "\n").trim();

    async.each(input.community, function (community, callbackInner) {
        Users.findOne({community: community, userType: 'service'}, function (err, service) {
            if (service == null) {
                Users.findOne({mobilePhone: '66customerservice'}, function (err, service) {
                    exports.saveQuestion(input, community, service, callbackInner);
                })
            } else {
                exports.saveQuestion(input, community, service, callbackInner);
            }
        })
    }, callback);
};

exports.MultipleAccountPostQuestionService = function (input, callback) {
    logger.debug(input);
    input.desc = input.desc.replace(/[\n\r]{2,}/g, "\n").trim();

    async.each(input.sendNumbers, function (sendNumber, callbackInner) {
        logger.debug(sendNumber);
        Users.findOne({huanxinUserName: sendNumber}, function (err, user) {
            if (user == null) {
                //Users.findOne({mobilePhone: '66customerservice'}, function (err, service) {
                //    exports.saveQuestion(input, community, service, callbackInner);
                //})
                callbackInner();
            } else {
                logger.debug(user);
                exports.saveQuestion(input, user.community, user, callbackInner);
            }
        })

    }, callback);
};


exports.saveQuestion = function (input, community, service, callback) {
    var questionId;
    async.series([
        function (c1) {
            if (input.category == 'neighbourActivity') {
                var activity = new neighbourActivity();
                activity.title = input.title;
                activity.desc = input.desc;
                activity.images = input.images;
                activity.deadline = input.deadline;
                activity.community = community;
                activity.activityType = Number(input.activityType);
                activity.createdBy = service._id;
                activity.tag = input.tag;
                questionId = activity._id;

                var key = 'activity:deadline';
                redisClient.zadd(key, input.deadline.getTime() / 1000, questionId + '');

                activity.save(c1);
            } else {
                var temp = new Question();
                temp.category = input.category;
                temp.desc = input.desc;
                temp.images = input.images;
                temp.createdBy = service._id;
                temp.community = community;
                temp.tag = input.tag;
                questionId = temp._id;
                temp.save(c1)
            }
        },
        function (c2) {
            redisClient.hincrby('q:count:' + community, input.category + 'QuestionCount', 1);

            var temp = new ugcIndex();
            temp.ugcId = questionId;
            temp.category = input.category;
            temp.community = community;
            temp.createdBy = service._id;
            temp.tag = input.tag;
            temp.save(c2);
        }
    ], callback);
};


exports.saveQuestionStoreService = function (input, callback) {

    input.desc = input.desc.replace(/[\n\r]{2,}/g, "\n").trim();

    logger.debug(input);
    if(input.type ==1) {
        var temp = new questionStore();
        temp.category = input.category;
        temp.desc = input.desc;
        temp.images = input.images;
        temp.tag = input.tag;

        temp.save(callback);
    }else{
        var opt = {

        }

        questionStore.update({_id: input.storeId}, opt, callbackInner);
    }
};


exports.getQuestionStoreService = function (page,size,input,callback) {

    var index = Number(input.page) *  Number(size);

    var opt={};

    if(input.desc != null){
        opt['desc'] = new RegExp(input.desc);
    };

    if(input._id != null){
        opt['_id'] = input._id;
    };


    async.series([

        function (callback) {
            questionStore.count(opt, function (err, count) {
                callback(err, Math.ceil(count / size));
            });
        },
        function (callback) {
            questionStore.find(opt).skip(index).limit(size).populate('tag', 'value').sort('-dateCreated')
                .exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        callback(null, results);
                    }
                });
        }
    ], callback);

};


exports.deleteQuestionStoreService = function (id, callback) {
    questionStore.findOneAndRemove({_id: id}, callback);
};

exports.updateQuestionStoreService = function (questionId, input, callback) {
    questionStore.update({_id: questionId}, input).exec(callback);
};


exports.createQuestionOrActivitService = function ( input, callback) {
    var opt = {};
    //logger.debug(input);

    var queryUserIn = {};
    queryUserIn["$in"] = input.community;

    if (input.community.length == 1) {
        opt["community"] = input.community[0];
    } else {
        opt["community"] = queryUserIn;
    }
    if(input.userType != null){
        opt["userType"] = input.userType;
    }

    //logger.debug(opt);
    User.find(opt).populate('community', '_id communityName').exec(function (err, results) {
        if (results != null) {
            logger.debug(input.images);

            var option = {
                desc : input.desc
            };
            if(input.images != null){
                option.images = input.images;
            }
            async.each(results, function (user, callbackInner) {

                restClient.get('http://' + AppHost + '/rest/v1.0/System/userToken/'+ user.huanxinUserName, function (data, response) {

                        var tokenData = JSON.parse(data);
                        //发活动
                        if (input.category == "neighbourActivity") {

                        option.title = input.title;
                        option.activityType = input.activityType;
                        option.deadline = input.deadline;

                        var args = {
                                data: option,
                                headers: {"Content-Type": "application/json"}
                            };

                        //发活动
                        restClient.post('http://' + AppHost + '/rest/v1.0/activity/newActivity/' + tokenData.data.token + '/' + 'PC', args, function (data, res) {
                            callbackInner(null, res);
                        }).on('error', function (err) {
                            logger.error('newActivity:' + err.message);
                            callbackInner(err, null);
                        });;

                    } else {
                        //发帖
                        option.category = input.category;
                        option.tag = input.tag;
                        var args = {
                            data: option,
                            headers: {"Content-Type": "application/json"}
                        };
                        //发帖子
                        restClient.post('http://' + AppHost + '/rest/v1.0/Questions/newQuestion/' + tokenData.data.token + '/' + 'PC', args, function (data, res) {
                            callbackInner(null, res);
                        }).on('error', function (err) {
                            logger.error('newQuestion:' + err.message);
                            callbackInner(err, null);
                        });
                    };
                });

            }, callback);


        }else {
            var msg = {
                "message": 'No such mobile'
            };
            callback(msg, null);
        }
    });


};

exports.getCardByFilterService = function (input,callback) {

    var opt = {};
    //beginTime:{type:Date},
    //endTime:{type:Date},
    switch(input.status){
        case '1':
            //小于开始日期
            //"$lte": moment(option['enddate']).add(1, 'day')._d
            opt.beginTime = {"$gte": new Date(moment())};
            break;
        case '2':
            opt = {
                beginTime:  {"$lte": new Date(moment())},
                endTime:    {"$gte": new Date(moment())}
            };
            break;
        case '3':
            opt.endTime = {"$lte": new Date(moment())};
            break;
        case '9':
            opt = input.filters;
            break;
        default:
            opt = {};
    };
    logger.debug(opt);
    Card.find(opt).sort({"displayOrder":-1}).exec(function (err, results) {
        if (results == undefined || results == null) {
            var msg = {
                "message": 'get err'
            };
            callback(msg, null);
        } else {
            callback(null, results);
        }
    });

};

exports.saveCardService = function (input, callback) {
    logger.debug(input);

    if(input.flg ==1) {
        var temp = new Card();
        temp.contentId = input.contentId;
        temp.contentUrl = input.contentUrl;
        temp.contentTitle = input.contentTitle,
        temp.title = input.title;
        temp.desc = input.desc;
        temp.imageURL = input.imageURL;
        temp.type = input.type;
        temp.openType = input.openType;
        temp.beginTime = input.beginTime;
        temp.endTime = input.endTime;

        temp.save(callback);
    }else{

        Card.update({_id: input.cardId}, input.option, callback);
    };
};

exports.deleteCardService = function (id, callback) {
    Card.findOneAndRemove({_id: id}, callback);
};

exports.setCardOrderService = function (input, callback) {
    var a = input.length;
    logger.debug(input);
    logger.debug(a);
    async.eachSeries(input, function (cardId, callbackInner) {
        Card.update({_id: cardId}, {displayOrder: a}, function (err, result) {
            logger.debug(a);
            a--;
            callbackInner(err, result);
        })
    }, function (err) {
        callback(err, null);
    })
};